package com.kaifamiao.wendao.filter;

import javax.servlet.*;
import java.io.IOException;
import java.nio.charset.Charset;

public class CharacterEncodingFilter implements Filter {

    private String encoding ;

    @Override
    public void init( FilterConfig config ) throws ServletException {
        // getInitParameter 参数中的 encoding 指 "<param-name>encoding</param-name>" 中的 encoding
        encoding = config.getInitParameter( "encoding" );
        encoding = encoding == null || encoding.trim().isEmpty() ? "UTF-8" : encoding.trim();
        encoding = Charset.isSupported( encoding ) ? encoding : "UTF-8" ;
    }

    @Override
    public void doFilter( ServletRequest req , ServletResponse resp , FilterChain chain )
            throws IOException, ServletException {
        req.setCharacterEncoding( encoding );
        resp.setCharacterEncoding( encoding );
        chain.doFilter( req , resp );
    }

    @Override
    public void destroy() {
    }

}
